package com.example.blog.controller.admin;

import com.example.blog.dao.FriendMapper;
import com.example.blog.pojo.FriendLink;
import com.example.blog.service.FriendService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @author: admin
 * @date: 2020/9/5
 */
@Controller
@RequestMapping("/admin")
public class FriendController {
    private final static String FRIEND_PAGE = "admin/friendlinks";
    private final static String FRIEND_PAGE_INPUT = "admin/friendlinks-input";
    @Resource
    private FriendService friendService;
    @GetMapping("/friend")
    public String toFriendPage(Model model){
        List<FriendLink> friendLink = friendService.getAllFriendLink();
        model.addAttribute("friendLink",friendLink);
        return FRIEND_PAGE;
    }
    @PostMapping("/friend")
    public String toFriendPage(FriendLink friendLink,RedirectAttributes redirectAttributes){
        String message = "修改成功";
        try {
            friendService.saveFriendLink(friendLink);
        } catch (Exception e) {
            message = "修改失败";
        }
        redirectAttributes.addAttribute("message",message);
        return "redirect:/admin/friend";
    }
    @GetMapping("/friend/{id}/input")
    public String toFriendInupt(@PathVariable Long id, Model model){
        FriendLink friendLink = null;
        if (id > 0) {
            friendLink = friendService.getFriendLink(id);
        } else {
            friendLink = new FriendLink();
        }
        model.addAttribute("friendLink",friendLink);
        return FRIEND_PAGE_INPUT;
    }
    @GetMapping("/friend/{id}/delete")
    public String delFriend(@PathVariable Long id , RedirectAttributes redirectAttributes){
        String message = "操作成功";
        try {
            friendService.deleteFriendLink(id);
        } catch (Exception e) {
            message = "操作失败";
        }
        redirectAttributes.addAttribute("message",message);
        return "redirect:/admin/friend";
    }
}
